package com.llkj.qingnianguoxue.book;

import android.Manifest;
import android.content.Intent;
import android.os.Bundle;
import android.util.Log;

import com.github.barteksc.pdfviewer.PDFView;
import com.github.barteksc.pdfviewer.listener.OnLoadCompleteListener;
import com.github.barteksc.pdfviewer.listener.OnPageChangeListener;
import com.github.barteksc.pdfviewer.scroll.DefaultScrollHandle;
import com.llkj.qingnianguoxue.R;
import com.llkj.qingnianguoxue.base.BaseActivity;
import com.llkj.qingnianguoxue.http.HttpMethod;
import com.llkj.qingnianguoxue.util.StringUtils;
import com.llkj.qingnianguoxue.util.ToastUtil;
import com.llkj.qingnianguoxue.util.Utils;
import com.tbruyelle.rxpermissions.RxPermissions;
import com.zhy.http.okhttp.OkHttpUtils;
import com.zhy.http.okhttp.callback.FileCallBack;

import java.io.File;

import okhttp3.Call;
import rx.functions.Action1;

/**
 * 阅读图书
 */
public class ReadBookActivity extends BaseActivity implements OnPageChangeListener, OnLoadCompleteListener {
    private PDFView pdfView;//pdf阅读器
    private String mPdfUrl;//pdf文件下载地址
    private String mFileName;//要保存的文件名字
    private boolean isPermissions;//读写文件权限
    private int mTotalPages, mCurrentPage;//总页数,当前page
    private String mBookId;//图书id
    private long mStartTime;
    private float mPercent;
    private static final String REFRESH_BOOK_STATE = "refresh_book_state";
    private boolean UPDATE = false;
    public static int CURRENTPAGE ;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_read_book);
        setTitle("阅读图书", true, TITLE_TYPE_IMG, R.drawable.icon_back, false, -1, -1);
        new RxPermissions(this)
                .request(Manifest.permission.WRITE_EXTERNAL_STORAGE, Manifest.permission.READ_EXTERNAL_STORAGE)
                .subscribe(new Action1<Boolean>() {
                    @Override
                    public void call(Boolean aBoolean) {
                        isPermissions = aBoolean;
                    }
                });

        Intent intent = getIntent();
        Bundle bundle = intent.getExtras();

        initView();
        initListener();

        mStartTime = System.currentTimeMillis();
        if (bundle != null) {
            mBookId = bundle.getString("id");
            mPdfUrl = bundle.getString("pdfUrl");
            mCurrentPage = Integer.parseInt(bundle.getString("readPage"));
            try {
                String percent = bundle.getString("percent");//百分比
                percent = percent.substring(0, percent.length() - 1);
                mPercent = Float.parseFloat(percent);
            } catch (Exception e) {
                e.printStackTrace();
            }
            mFileName = bundle.getString("bookName") + ".pdf";

            downloadPdfFile();
        }
    }

    private void initView() {
        pdfView = (PDFView) findViewById(R.id.pdfView);
    }

    private void initListener() {
    }

    private void loadPdf(File pdfFile) {
        try {
            pdfView.fromFile(pdfFile)
                    .defaultPage(mCurrentPage)
                    .onPageChange(this)
                    .onLoad(this)
                    .enableSwipe(true)
//                    .swipeHorizontal(true)
                    .enableAnnotationRendering(true)
                    .scrollHandle(new DefaultScrollHandle(this))
                    .load();
        } catch (Exception e) {
            ToastUtil.makeLongText(this, "文件损坏，或者不是一个pdf文件格式");
            e.printStackTrace();
        }
    }

    /**
     * 文件下载
     */
    private void downloadPdfFile() {
        if (!isPermissions) {
            ToastUtil.makeLongText(this, "对不起，没有获取到读取文件权限");
            return;
        }
        loadWaitDialog();
        final String dir = Utils.getAppBooksDir(getApplicationContext());
        File bookFile = getAllFiles(new File(dir));
        if (bookFile != null && bookFile.exists() && bookFile.isFile()) {
            loadPdf(bookFile);
            return;
        }

        if (StringUtils.isEmpty(mPdfUrl) || StringUtils.isEmpty(mFileName)) {
            ToastUtil.makeLongText(this, "对不起，图示加载失败");
            dismissWaitDialog();
            return;
        }

        new File(dir).mkdirs();
        //需要优化，判断是否下载过
        OkHttpUtils//
                .get()//
                .url(mPdfUrl)//
                .build()//
                .execute(new FileCallBack(dir, mFileName) {
                    @Override
                    public void onError(Call call, Exception e, int id) {
                        dismissWaitDialog();
                        ToastUtil.makeLongText(ReadBookActivity.this, "对不起，图书加载失败");
                    }

                    @Override
                    public void onResponse(File response, int id) {
                        if (response != null && response.exists() && response.isFile()) {
                            loadPdf(response);
//                                    pdfView.fromFile(response);
                        } else {
                            dismissWaitDialog();
                            ToastUtil.makeLongText(ReadBookActivity.this, "对不起，图书加载失败");
                        }
                    }
                });
    }


    @Override
    protected void leftDoWhat() {
        onBackPressed();
    }

    @Override
    public void onBackPressed() {
        dealBeforeFinish();
        super.onBackPressed();
    }

    /**
     * 遍历获取本地文件
     * 遍历接收一个文件路径，然后把文件子目录中的所有文件遍历并输出来
     */
    private File getAllFiles(File root) {
        File files[] = root.listFiles();
        File bookFile = null;
        if (files != null) {
            for (File f : files) {
                if (f.isDirectory()) {
                    bookFile = getAllFiles(f);
                } else {
                    String fileName = f.getName();
                    if (mFileName.equals(fileName)) {
                        return f;
                    }
                }
            }
        }
        return bookFile;
    }

    @Override
    public void loadComplete(int nbPages) {
        mTotalPages = nbPages;
        dismissWaitDialog();
        Log.e("Log", "加载完成====" + nbPages);
//        try {
//            float defaultPage = mPercent/100;
//            pdfView.setPositionOffset(defaultPage);
//        } catch (Exception e) {
//            e.printStackTrace();
//        }
    }

    @Override
    public void onPageChanged(int page, int pageCount) {
        if (!UPDATE){
            UPDATE = true;
            return;
        }
        Log.e("Log", "界面变化====" + page + ";;;;" + pageCount);
        page += 1;
//        if (page > mCurrentPage) {
        mCurrentPage = page;
//        float percent = page / mTotalPages;
//        String per = String.format("%.2f", percent);
//        long timeSeconds = (System.currentTimeMillis() - mStartTime) / 1000;
//        HttpMethod.readLong(this, this, String.valueOf(timeSeconds), mBookId, String.valueOf(page));
//        }
    }

    @Override
    protected void onhttpSuccess(String data, int method) {
        super.onhttpSuccess(data, method);
        if (method == HttpMethod.HTTP_HANDPIC_BOOKS_READ) {
//            Intent intent = new Intent();
//            int p = 100 * mCurrentPage / mTotalPages;
//            intent.putExtra("percent", String.valueOf(p) + "%");
//            intent.putExtra("page", String.valueOf(mCurrentPage));
//            setResult(RESULT_OK, intent);
        }
    }

    protected void dealBeforeFinish() {
        try {
            CURRENTPAGE = mCurrentPage;
            float percent = mCurrentPage / mTotalPages;
            String per = String.format("%.2f", percent);
            long timeSeconds = (System.currentTimeMillis() - mStartTime) / 1000;
//            HttpMethod.readLong(this, this, String.valueOf(timeSeconds), mBookId, String.valueOf(mCurrentPage));
            Intent intent = new Intent();
            int p = 100 * mCurrentPage / mTotalPages;
            intent.putExtra("percent", String.valueOf(p) + "%");
            intent.putExtra("page", String.valueOf(mCurrentPage));
            setResult(RESULT_OK, intent);
//        RxBus.getInstance().post(REFRESH_STATE);
        }catch (Exception e){}
    }
}
